<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%
    request.setCharacterEncoding("UTF-8");
    if (session.getAttribute("isLoggedIn") == null || (!"true".equals(session.getAttribute("isLoggedIn").toString()))) {
        response.sendRedirect( "index.jsp" );
    }
%>

<%
    String savePath = "", filepath = "", filename = "";
    String contentType = "", fileData = "", strLocalFileName = "";
    int startPos = 0, endPos = 0;
    int BOF = 0, EOF = 0;
%>
<%!
    //copy specified number of bytes from main data buffer to temp data buffer
    void copyByte(byte[] fromBytes, byte[] toBytes, int start, int len) {
        for (int i = start; i < (start + len); i++) {
            toBytes[i - start] = fromBytes[i];
        }
    }
%>
<%
    contentType = request.getContentType();
    //System.out.println("<br>Content type is :: " + contentType);
    String status = "no";
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        DataInputStream in1 = in;
        int formDataLength = request.getContentLength();

        if (formDataLength > 100 * 1024) {
            status = "toobig";

        } else {
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            while (totalBytesRead < formDataLength) {
                byteRead = in1.read(dataBytes, totalBytesRead, formDataLength);
                totalBytesRead += byteRead;
            }
            ///System.out.println("<br>totalBytesRead : " + totalBytesRead + "    :   formDataLength = " + formDataLength);

            //String file = new String(dataBytes);
            //System.out.println("<br>File Contents:<br>////////////////////////////////////<br>" + file + "<br>////////////////////////////////<br>");

            byte[] line = new byte[128];
            if (totalBytesRead < 3) {
                return;    //exit if file length is not sufficiently large
            }

            String boundary = "";
            String s = "";
            int count = 0;
            int pos = 0;

            //loop for extracting boundry of file
            //could also be extracted from request.getContentType()
            do {
                copyByte(dataBytes, line, count, 1);    //read 1 byte at a time
                count += 1;
                s = new String(line, 0, 1);
                fileData = fileData + s;
                pos = fileData.indexOf("Content-Disposition: form-data; name=\""); //set the file name
                if (pos != -1)
                    endPos = pos;
            } while (pos == -1);
            boundary = fileData.substring(startPos, endPos);

            //loop for extracting filename
            startPos = endPos;
            do {
                copyByte(dataBytes, line, count, 1);    //read 1 byte at a time
                count += 1;
                s = new String(line, 0, 1);
                fileData = fileData + s;
                pos = fileData.indexOf("filename=\"", startPos); //set the file name
                if (pos != -1)
                    startPos = pos;
            } while (pos == -1);

            do {
                copyByte(dataBytes, line, count, 1);    //read 1 byte at a time
                count += 1;
                s = new String(line, 0, 1);
                fileData = fileData + s;
                pos = fileData.indexOf("Content-Type: ", startPos);
                if (pos != -1)
                    endPos = pos;
            } while (pos == -1);

            filename = fileData.substring(startPos + 10, endPos - 3);    //to eliminate " from start & end
            strLocalFileName = filename;
            int index = filename.lastIndexOf("\\");
            if (index != -1)
                filename = filename.substring(index + 1);

            //loop for extracting ContentType
            boolean blnNewlnFlag = false;
            startPos = endPos;    //added length of "Content-Type: "
            do {
                copyByte(dataBytes, line, count, 1);    //read 1 byte at a time
                count += 1;
                s = new String(line, 0, 1);
                fileData = fileData + s;

                pos = fileData.indexOf("\n", startPos);
                if (pos != -1) {
                    if (blnNewlnFlag == true)
                        endPos = pos;
                    else {
                        blnNewlnFlag = true;
                        pos = -1;
                    }
                }
            } while (pos == -1);
            contentType = fileData.substring(startPos + 14, endPos);

            //loop for extracting actual file data (any type of file)
            BOF = count +1;
            do {
                copyByte(dataBytes, line, count, 1);    //read 1 byte at a time
                count += 1;
                s = new String(line, 0, 1);
                fileData = fileData + s;
                pos = fileData.indexOf(boundary, startPos);    //check for end of file data i.e boundry value
            } while (pos == -1);
            EOF = count - boundary.length() - 2;

            //create destination path & save file there
            String appPath = application.getRealPath("/");
            System.out.println("appPath:  " + appPath);

            byte[] bytePath = appPath.getBytes();
            int length = bytePath.length;
            int j = 0;
            int c = 0;

            for (int i = length - 1; i >= 0; i--) {
                if (bytePath[i] == '\\') {
                    if (c == 2) {
                        j = i + 1;
                        i = -1;
                    }
                    c++;
                }
            }

            byte[] newByte = new byte[j]; 
            for (int i = 0; i < j; i++) {
                newByte[i] += bytePath[i];
            }

            appPath = new String(newByte);

            String destFolder = appPath + "syndicates/" + session.getAttribute("login") + "/";    //change this as required
            String fullFilename = destFolder + filename;
            try {
                File dir = new File(destFolder);
                dir.mkdirs();
                FileOutputStream fileOut = new FileOutputStream(fullFilename);
                fileOut.write(dataBytes, BOF, (EOF - BOF));
                fileOut.flush();
                fileOut.close();
                status = "yes";
                Class.forName("org.h2.Driver");
                Connection conn;
                try {
                    conn = DriverManager.getConnection("jdbc:h2:file:/data/compwars.db", "sa", "");
                    Statement sql = conn.createStatement();
                    ResultSet rs = sql.executeQuery("SELECT * FROM GANGSTERS where jarfile='"+filename+"' and teamid="+session.getAttribute("id")+" LIMIT 1");
                    if (!rs.next()){
                        String query = "INSERT INTO GANGSTERS(teamid, name, jarfile, fullpath) VALUES(\'" + session.getAttribute("id") + "\', \'"
                                + filename.substring(0,filename.length()-4) + "\', \'" + filename
                                + "\', \'" + fullFilename + "\');";
                        System.out.println(query);
                        sql.execute(query);
                    }
                    conn.close();
                } catch (SQLException e) {
                    status = "sql";
                    System.out.println("SQL exception: " + e.getMessage());
                }
            } catch (IOException e) {
                status = "no";
            }
        }
    } else {
        System.out.println("Error in uploading ");
    }

%>


<html>
<head>
    <meta http-equiv="refresh" content="0;URL=gangsters.jsp?status=<%=status%>">
    <title>
    </title>
</head>
<body>
</body>
</html>